<template>
  <div class="page">
    <div style="position: fixed; top: 0; width: 100%">
      <van-search
        v-model="searchVal"
        show-action
        placeholder="请输入搜索关键词"
        @search="onSearch"
        @cancel="onCancel"
        @update:model-value="onchange"
        @focus="onfocus"
      />
      <ul class="keywordPrefix" v-show="showPrefix">
        <li v-for="(item, index) in keywordPrefix" :key="index" @click="handelkeywordPrefix(item)">
          <span>{{ item }}</span>
          <van-icon name="arrow" class="arrow" />
        </li>
      </ul>
    </div>

    <VSearList v-if="keyWord.length === 0 ? false : true" :keyWord="keyWord" />
    <div
      style="position: fixed; top: 54px"
      v-show="searchVal.length === 0 ? true : false && keywordPrefix.length !== 0"
    >
      <div class="histroySearch" v-show="hostrySearchVal.length === 0 ? false : true">
        <div style="overflow: hidden">
          <div class="text">历史记录</div>
          <van-icon class="delIcon" name="delete-o" @click="delhistroySearch" />
        </div>
        <div class="recording">
          <a v-for="(item, index) in hostrySearchVal" :key="index" @click="handelSearch(item)">
          {{
            item
          }}</a>
        </div>
      </div>

      <div class="hotSearch">
        <div style="overflow: hidden">
          <div class="text">热门搜索</div>
        </div>
        <div class="recording">
          <a
            v-for="(item, index) in hotSearchVal"
            :key="index"
            :class="item.highlight === 1 ? 'highlight' : ''"
            @click="handelSearch(item.keyword)"
            >{{ item.keyword }}</a
          >
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, ref } from 'vue'
import { reqHotSearch, reqSearch } from '@/api/search'
import router from '@/router'
//引入搜索列表组件
import VSearList from './searchList/searchList.vue'
import type { IKeyword } from '@/types/search'
//定义热门搜索数据
const hotSearchVal = ref<IKeyword[]>()
//定义默认搜索词
const defaultKeyword = ref<IKeyword>()
//定义搜索框内容
const searchVal = ref('')
// //定义搜索记录
const hostrySearchVal = ref<string[]>([])
//定义是否存在关键字
const keyWord = ref('')
//联想数据
const keywordPrefix = ref<string[]>([])

const showPrefix = ref(false)

//搜索事件
let timeId = setTimeout(() => {}, 500)
const onSearch = () => {
  clearTimeout(timeId)
  saveSearchval()
  showPrefix.value = false
  router.push(`/search?keyword=${searchVal.value}`)
  keyWord.value = searchVal.value
}
//即时搜索
const onchange = () => {

  clearTimeout(timeId)
  timeId = setTimeout(async () => {
    let res = await reqSearch(searchVal.value)
    if (res.code === '200') {
      keywordPrefix.value = res.data
      showPrefix.value = true
    }
  }, 500)
}
//输入框获取焦点
const onfocus = async () => {
  keyWord.value = ''
  showPrefix.value =true
  let res = await reqSearch(searchVal.value)
  if (res.code === '200') {
    keywordPrefix.value = res.data
  }
}

//点击联想搜索关键字
const handelkeywordPrefix = (val: string) => {
  searchVal.value = val
  keywordPrefix.value = []
  onSearch()
}
//点击搜索框后的取消按钮
const onCancel = () => {
  if (searchVal.value.length !== 0) {
    searchVal.value = ''
    keyWord.value = ''
  } else {
    router.push(`/home`)
  }
}

//搜索记录和热门搜索点击
const handelSearch = (value: string) => {
  console.log(value)
  searchVal.value = value
  keyWord.value = value
  saveSearchval()
  router.push(`/search?keyword=${value}`)
}

//删除搜索记录
const delhistroySearch = () => {
  hostrySearchVal.value = []
  localStorage.removeItem('hostryVal')
}

//储存搜索记录
const saveSearchval = () => {
  if (hostrySearchVal.value.length === 0) {
    hostrySearchVal.value.unshift(searchVal.value)
    localStorage.setItem('hostryVal', JSON.stringify(hostrySearchVal.value))
  }
  let isRepeat = hostrySearchVal.value.find((item) => item === searchVal.value)
  if (!isRepeat) {
    hostrySearchVal.value.unshift(searchVal.value)
    localStorage.setItem('hostryVal', JSON.stringify(hostrySearchVal.value))
  }
}

//获取搜索历史
const getHstoryVal = () => {
  const hostryVal = JSON.parse(localStorage.getItem('hostryVal') as string)
  hostrySearchVal.value = hostryVal || []
}

//获取及默认搜索词热门搜索词
const getHotVal = async () => {
  let res = await reqHotSearch()

  if (res.code === '200') {
    hotSearchVal.value = res.data.hotKeywordVOList
    defaultKeyword.value = res.data.defaultKeyword
  }
}

onMounted(() => {
  getHstoryVal()
  getHotVal()
})
</script>

<script lang="ts">
export default {
  name: 'VueSearch'
}
</script>

<style lang="scss" scoped>
.page {
  width: 100%;
  height: 100%;
  background-color: #eee;
  .keywordPrefix {
    li {
      &:not(:nth-child(1)) {
        border-top: 1.5px solid rgb(212, 206, 206);
      }
      .arrow {
        line-height: 48px;
        margin-right: 20px;
        font-size: 17px;
      }
      box-sizing: border-box;
      font-size: 14px;
      height: 48px;
      margin-left: 15px;
      line-height: 48px;
      display: flex;
      justify-content: space-between;
    }
  }
  .histroySearch,
  .hotSearch {
    background-color: white;
    padding: 15px;
    margin-bottom: 15px;

    .text {
      float: left;
      font-size: 15px;
      color: #999;
    }
    .delIcon {
      float: right;
      font-size: 18px;
      color: #999;
    }
    .recording {
      .highlight {
        border: 1px solid rgb(240, 38, 38);
        color: rgb(240, 38, 38);
      }
      a {
        display: block;
        float: left;
        font-size: 10px;
        border: 1px solid rgb(72, 70, 70);
        border-radius: 4px;
        height: 23px;
        padding: 2px 7.5px;
        line-height: 23px;
        margin-right: 18px;
        margin-bottom: 15px;
      }
      margin-top: 15px;
      overflow: hidden;
    }
  }
}
</style>
